<template>
  <div>
    <el-upload
      class="upload-demo"
      :headers="headers"
      :action="ports"
      multiple
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :show-file-list="false"
      :on-exceed="handleExceed"
    >
      <img v-if="image" :src="image" alt="" style="width: 178px; height: 178px" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </div>
</template>
<script setup lang="ts">
import { reactive, watchEffect, ref } from "vue";
import { useUserStore } from "@/stores/modules/user";
import type { UploadProps } from "element-plus";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
const image = ref("");
const ports = ref();
const userStore = useUserStore();
// 接收父组件传来的数据
const props = defineProps({
  port: {
    type: String as any,
    default: () => ""
  },
  imgurl: {
    type: String as any,
    default: () => ""
  }
});
watchEffect(() => {
  ports.value = props.port;
  image.value = props.imgurl ? props.imgurl : image.value;
  console.log(props.imgurl, "image.valueimage.valueimage.value");
});

const emit = defineEmits(["uploadsuccess"]);

// 上传token
let headers = reactive<any>({
  Authorization: `Bearer ${userStore.token}`
});

const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  image.value = URL.createObjectURL(uploadFile.raw!);
  console.log(image.value);

  if (response.Success == 0) {
    emit("uploadsuccess", response.Data);
  }
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  console.log(rawFile.type);

  if (rawFile.type !== "image/png" && rawFile.type !== "image/jpeg") {
    ElMessage.error("上传图片的格式错误");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 3) {
    ElMessage.error("不能删除大于三MB的图片1");
    return false;
  }
  return true;
};

const handleExceed: UploadProps["onExceed"] = () => {
  ElMessage.warning(`只能上传一次`);
};
defineExpose({
  image
});
</script>

<style scoped>
.avatar-uploader .avatar {
  display: block;
  width: 178px;
  height: 178px;
}
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
  border: 2px dashed #8c939d;
}
</style>
